import { decode, encode } from "cbor-x";

let BASE_URL = `http://${window.location.host}/api`;

if (import.meta.env.MODE === 'development') {
    // 在开发模式下的逻辑
    BASE_URL = "http://localhost:5173/api";
}

const HEAD_RESP_TYPE = "RESP-TYPE";
const HEAD_TYPE_OK = "OK";
const HEAD_TYPE_ERR = "ERR";

export interface ErrMsg {
    err_code: number,
    err_msg: string,
}

export function cborEncode<T>(obj: T) {
    const r = encode(obj);
    return r;
}

export function cborDecode<T>(buf: ArrayBuffer) {
    return decode( new Uint8Array(buf) ) as T
}

export async function serverGet2<R>(url: string) {
    const resp = await fetch(`${BASE_URL}${url}`, {
        method: 'POST',
    });
    const type = resp.headers.get(HEAD_RESP_TYPE);
    if (type == null) {
        throw 'invalid resp';
    }
    if (type == HEAD_TYPE_ERR) {
        const err = cborDecode<ErrMsg>(await resp.arrayBuffer());
        throw `code:${err.err_code} msg:${err.err_msg}`;
    } else if (type == HEAD_TYPE_OK) {
        return cborDecode<R>(await resp.arrayBuffer());
    }
    throw 'invalid resp2';
}

export async function serverGet<T, R>(url: string, body: T) {
    const data = cborEncode<T>(body);
    const resp = await fetch(`${BASE_URL}${url}`, {
        method: 'POST',
        body: data,
    });
    const type = resp.headers.get(HEAD_RESP_TYPE);
    if (type == null) {
        throw 'invalid resp';
    }
    if (type == HEAD_TYPE_ERR) {
        const err = cborDecode<ErrMsg>(await resp.arrayBuffer());
        throw `code:${err.err_code} msg:${err.err_msg}`;
    } else if (type == HEAD_TYPE_OK) {
        return cborDecode<R>(await resp.arrayBuffer());
    }
    throw 'invalid resp2';
}



